package org.ucn.dmaa0914.temadesign.group2.modelLayer;
import java.util.HashSet;
import java.util.Iterator;

/**
 * The person container class is responsible of containing all persons and perform lookups.
 * 
 * @author Kim Johannsen
 * @version 04-11-2014
 */
public class PersonContainer
{
    HashSet<Person> personCollection;
    
    // Provide a singleton instance, as this class is only ment to be instantiated once per program.
    public static final PersonContainer instance = new PersonContainer();
    
    /**
     * Constructor
     */
    public PersonContainer()
    {
        personCollection = new HashSet<Person>();
    }
    
    /*
     * Adds a person to the container, if it doesnt already exist
     * in the database.
     * 
     * @param p The person to add
     * @return True if the person was added. False if the person was already added.
     */
    public boolean addPerson(Person p)
    {
        return personCollection.add(p);
    }
    
    /**
     * Checks whether this container has a person.
     * 
     * @param p The person to check for
     * @return True if this container has this person. False if not.
     */
    public boolean containsPerson(Person p)
    {
        return personCollection.contains(p);
    }
    
    /**
     * Looks up a person by he's id.
     * 
     * @param id The id of the person to find.
     * @return The person with the specified id, or null if the person is not found.
     */
    public Person findPerson(int id)
    {
        Iterator<Person> i = personCollection.iterator();
        
        while( i.hasNext() )
        {
            Person p = i.next();
            
            if( p.getId() == id )
            {
                return p;
            }
        }
        
        return null;
    }
    
    /**
     * Looks up a person by he's phone number.
     * 
     * @param phone The phone number of the person to look for
     * @return The person with the specified phone number, or null if the person is not found.
     */
    public Person getPerson(String phone)
    {
        Iterator<Person> i = personCollection.iterator();
        
        while( i.hasNext() )
        {
            Person p = i.next();
            
            if( p.getPhone().equals(phone) )
            {
                return p;
            }
        }
        
        return null;
    }
    
    /**
     * Deletes a person from the container if present
     * 
     * @param p The person to delete
     */
    public void deletePerson(Person p)
    {
        personCollection.remove(p);
    }
    
    /**
     * Retrieves all persons in the container
     */
    public HashSet<Person> getAll()
    {
        return personCollection;
    }
   
}
